package org.fioma.ui;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.fioma.tree.bytes.Tools;

public class FastQ {

	String fileFastQName;
	int k; // sequence length must be greater than k
	BufferedReader br;

	String line = null;
	int pos = 0; // position in the line to start the new sequence

	public FastQ(String fileFastQName, int k) throws FileNotFoundException {
		this.fileFastQName = fileFastQName;
		this.k = k;

		br = new BufferedReader(new FileReader(fileFastQName));

	}

	public byte[] getNextSeq() throws IOException {
		byte[] ret = null;
		String seqInTheLine;
		while (ret == null && (((seqInTheLine = getNextSeqInTheLine()) != null) || (line = getNextLine()) != null)) {
			if (seqInTheLine == null) {
				seqInTheLine = getNextSeqInTheLine();
			}
			if (seqInTheLine != null && seqInTheLine.length() >= k) {
				ret = Tools.transformToBytes(seqInTheLine.toCharArray());
			}
		}
		return ret;
	}

	public String getNextSeqInTheLine() {
		String ret = null;
		if (line != null && pos < line.length()) {
			for (; pos < line.length() && (line.charAt(pos) == 'N' || line.charAt(pos) == 'n'); pos++) {

			}

			if (pos < line.length()) {
				StringBuffer ret1 = new StringBuffer();
				for (; pos < line.length() && (line.charAt(pos) != 'N' && line.charAt(pos) != 'n'); pos++) {
					ret1.append(line.charAt(pos));
				}
				ret = ret1.toString();
			}
		}
		return ret;
	}

	public String getNextLine() throws IOException {
		String ret = null;
		if ((br.readLine()) != null) {
			ret = br.readLine().trim();
			pos = 0;
			br.readLine();
			br.readLine();
		}
		return ret;

	}

}
